import { themePreprocessorPlugin } from '@pureadmin/theme'
import vue from '@vitejs/plugin-vue'
import jsx from '@vitejs/plugin-vue-jsx'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import DefineOptions from 'unplugin-vue-define-options/vite'
import { type ConfigEnv, loadEnv, type UserConfigExport } from 'vite'
import removeConsole from 'vite-plugin-remove-console'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import svgLoader from 'vite-svg-loader'
import { cdn } from './build/cdn'
import { configCompressPlugin } from './build/compress'
import { viteBuildInfo } from './build/info'
import { __APP_INFO__, alias, pathResolve, processEnv, root } from './build/utils'
import { genScssMultipleScopeVars } from './src/layout/theme'

export default async ({ mode }: ConfigEnv): Promise<UserConfigExport> => {
  const { VITE_CDN, VITE_PORT, VITE_COMPRESSION, VITE_PUBLIC_PATH } = processEnv(
    loadEnv(mode, root)
  )
  const lifecycle = process.env.npm_lifecycle_event
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias,
    },
    // 服务端渲染
    server: {
      // 端口号
      port: VITE_PORT,
      host: '0.0.0.0',
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        '^/api/.*': {
          // 这里填写后端地址
          // target: 'http://10.1.0.136:32241',
          target: 'http://172.16.124.227:8082',
          // target: 'http://localhost:8082',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ['./index.html', './src/{views,components}/*'],
      },
    },
    plugins: [
      vue(),
      jsx(),
      DefineOptions(),
      viteBuildInfo(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(__dirname, 'src/assets/icons/svg')],
        symbolId: 'icon-[dir]-[name]',
      }),
      AutoImport({
        imports: ['vue', 'vue-router', '@vueuse/core'],
        resolvers: [ElementPlusResolver()],
        dts: './types/auto-imports.d.ts',
      }),
      Components({
        dirs: ['src/components'],
        resolvers: [ElementPlusResolver()],
        globs: ['src/components/**/*.vue', '!src/components/ReIcon'],
        dts: './types/components.d.ts',
      }),
      configCompressPlugin(VITE_COMPRESSION),
      // 线上环境删除console
      removeConsole({ external: ['src/assets/iconfont/iconfont.js'] }),
      // 自定义主题
      themePreprocessorPlugin({
        scss: {
          multipleScopeVars: genScssMultipleScopeVars(),
          extract: true,
        },
      }),
      // svg组件化支持
      svgLoader({
        defaultImport: 'url',
      }),
      VITE_CDN ? cdn : null,
      // 打包分析
      lifecycle === 'report'
        ? visualizer({ open: true, brotliSize: true, filename: 'report.html' })
        : null,
    ],
    // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
    optimizeDeps: {
      /** 避免 vite 频繁优化 ep 的 css 依赖 */
      include: ['element-plus/es/**/css'],
      exclude: ['@iconify-icons/ep', '@iconify-icons/ri', '@pureadmin/theme/dist/browser-utils'],
    },
    build: {
      target: 'es2015',
      sourcemap: false,
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve('./index.html', import.meta.url),
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
  }
}
